<?php
/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// {{{ requires
require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php';

/**
 * 会員登録のページクラス.
 *
 * @package Page
 * @author LOCKON CO.,LTD.
 * @version $Id: LC_Page_Regist.php 21950 2012-07-02 11:42:51Z pineray $
 */
class LC_Page_Elect_Vote extends LC_Page_Ex {

    // {{{ properties

    // }}}
    // {{{ functions
    /**
     * Page を初期化する.
     *
     * @return void
     */
    function init() {
    		
        parent::init();
    	//权限验证
	    if($this->objSess->GetSession('cert')!= CERT_STRING){
	    	SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'please log in.');
	    }
		//引入本页面javascript
	   	$this->linkCss[] = 'css/sapaImport.css';
        $this->link_javascript[] = "js/sapa/jquery.dataTables.js";
        
    }

    /**
     * Page のプロセス.
     *
     * @return void
     */
    function process() {
        //parent::process();
        $this->action();
        $this->sendResponse();
    }

    /**
     * Page のAction.
     *
     * @return void
     */
    function action() {
        switch ($this->getMode()) {
        	case 'vote':
        		$this->insertToVoteTab();
        		SC_Response_Ex::sendRedirect(HTTP_URL."mypage/index.php");
                break;
            case 'showThisVote':
		        $this->tpl_mainpage = 'elect/elect_vote.tpl';
		        $this->getNewestElect();
            	break;
            default:
            	$this->tpl_mainpage = 'elect/can_vote_list.tpl';
		        $this->electInfoArr = $this->getMyElectInfo();
                break;
        }
    }

    /**
     * デストラクタ.
     *
     * @return void
     */
    function destroy() {
        parent::destroy();
    }
    
    function getNewestElect(){
    	$electionId = $this->getValFromPostOrGet("id");
    	if(!empty($electionId)){
    	
	    	$objQuery = SC_Query::getSingletonInstance();
			$electInfoArr = $objQuery->select('id,elect_title,start_time,close_time ','mst_elect','id = ? ',array($electionId));
			
			$this->electionTilte = $electInfoArr[0]['elect_title'];
			$this->electionId = $electInfoArr[0]['id'];
			$this->startDate = $electInfoArr[0]['start_time'];
			$this->endDate = $electInfoArr[0]['close_time'];
			
			//职位信息
	        $this->positionInfoArr = $objQuery->select('id,position_name,number_limite','tab_elect_position','elect_id=?' ,array($electionId));
	        $this->positionInfoArrSize = count($this->positionInfoArr);
	        $this->candidateArr = array();
	        //候选人信息
	        foreach ($this->positionInfoArr as $i =>$positionInfo) {
	        	
	        	$candidateInfoArr = $objQuery->select('id,candidature_name','tab_elect_candidate','elect_position_id=?' ,array($positionInfo['id']));
	        	
	        	$tempArr = array();
	        	foreach ($candidateInfoArr as $candidateInfo) {
	        		
	        		array_push($tempArr,$candidateInfo);
	        	}
	        	$this->candidateArr[] = $tempArr;
	        }  
    	}else {
    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'get data error.');
    	}
    }
    
    function insertToVoteTab(){
    	
    	$electionName = $this->getValFromPostOrGet('election');
    	$electionId = $this->getValFromPostOrGet('electionId');
    	
    	$positionIdArr = $this->getValFromPostOrGet('positionId');
    	$positionNameArr = $this->getValFromPostOrGet('positionName');
    	
    	$candidateIdArr  = $this->getValFromPostOrGet('candidateId');
    	
    	$objQuery = SC_Query::getSingletonInstance();
    	$objQuery->begin();
    	
    	foreach ($positionIdArr as $i =>$positionId) {
			foreach ($candidateIdArr[$i] as $candidateId) {
				$tabArr = array();
		        $tabArr['elect_id'] = $electionId;
				$tabArr['user_id'] = $this->objSess->GetSession('user_id');
				$tabArr['positio_id'] = $positionId;
				$tabArr['candidate_id'] = $candidateId;
				$tabArr['voter_lastname'] = $this->objSess->GetSession('lastname');
				$tabArr['voter_firstname'] = $this->objSess->GetSession('firstname');
				$tabArr['elect_name'] = $electionName;
				$tabArr['position_name'] = $positionNameArr[$i];
				$tempRs = $objQuery->select('candidature_name', 'tab_elect_candidate','id = ?', array($candidateId));
				$tabArr['candidature_lastname'] = $tempRs[0]['candidature_name'];
				$tabArr['del_flg'] = '0';
				$tabArr['create_time'] = 'now()';
				$tabArr['update_time'] = 'now()';

				$objQuery->insert('tab_vote',$tabArr);
			}
    	}
        
        
    	//插入数据库时 出错了	
		if ($objQuery->isError()) {
			$objQuery->rollback();
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
			break;
		}else{
			$objQuery->commit();
		}
    }
    
  	function getMyElectInfo(){
    	$rs = array();
    	$userId = $this->objSess->GetSession("user_id");
    	
    	$objQuery = SC_Query::getSingletonInstance();
    	$rs= $objQuery->select("*","mst_elect");
    	
    	$timeNow = date("Y-m-d");		
    	foreach ($rs as $key => $value) {
    		//
    		if($timeNow > $value['close_time']){
    			$rs[$key]['electStatus'] = "Ended";
    		}elseif($timeNow < $value['start_time']){
    			$rs[$key]['electStatus'] = "Waiting";
    		}else{
    			$rs[$key]['electStatus'] = "Active";
    		}
    		
    		//
    		if(!empty($userId)){
    			$count = $objQuery->count("tab_vote","elect_id = ? and user_id = ? ",array($value['id'],$userId));
    			 GC_Utils_Ex::gfPrintLog($count, '^^^^^^^^^^^^^^^^^');
    			//已经投过票
    			if($count >0){
					$rs[$key]['canVote'] = FALSE;
    			//还没投票
    			}else{
    				$rs[$key]['canVote'] = TRUE;
    			}
    		}
    	}
    	return $rs;
    }
}